package com.yejq.service.impl;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.yejq.Constants;
import com.yejq.service.BingbingdbService;

public class BingbingdbServiceImpl implements BingbingdbService {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<Map> showTableDatas(String path, String collectionName) throws Exception {
		List<Map> list = new ArrayList<Map>();
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File(path));
		Element root = doc.getRootElement();
		for (Iterator<?> iterator = root.elementIterator("table"); iterator.hasNext();) {
			Element element = (Element) iterator.next();
			if (element.attributeValue("name").equals(collectionName)) {
				for (Iterator<?> iterator2 = element.elementIterator("data"); iterator2.hasNext();) {
					Element data = (Element) iterator2.next();
					Gson gson = new Gson();
					Map<String, String> oldMap = gson.fromJson(data.getText(), Map.class);
					list.add(oldMap);
				}
			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean insert(String path, String collectionName, Object object) throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File(path));
		Element root = doc.getRootElement();
		for (Iterator<?> iterator = root.elementIterator("table"); iterator.hasNext();) {
			Element element = (Element) iterator.next();
			logger.debug("name:{}", element.attribute("name").getValue());
			if (element.attribute("name").getValue().equals(collectionName)) {
				Map<String, String> base = new HashMap<String, String>();
				base.put(Constants._id, UUID.randomUUID().toString());
				
				Gson gson = new Gson();
				String json = gson.toJson(object);
				base.putAll(gson.fromJson(json, Map.class));
				
				Element data = element.addElement("data");
				data.addText(gson.toJson(base));
			}
		}

		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(new FileWriter(path), format);
		writer.write(doc);
		writer.close();
		
		logger.info("insert data success!");
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(String path, String collectionName, Object object) throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File(path));
		Element root = doc.getRootElement();
		for (Iterator<?> iterator = root.elementIterator("table"); iterator.hasNext();) {
			Element element = (Element) iterator.next();
			if (element.attributeValue("name").equals(collectionName)) {
				for (Iterator<?> iterator2 = element.elementIterator("data"); iterator2.hasNext();) {
					Element data = (Element) iterator2.next();
					Gson gson = new Gson();
					Map<String, String> oldMap = gson.fromJson(data.getText(), Map.class);
					Map<String, String> newMap = gson.fromJson(gson.toJson(object), Map.class);
					if (oldMap.get(Constants._id).equals(newMap.get(Constants._id))) {
						data.setText(gson.toJson(newMap));
					}				
				}
			}
		}

		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(new FileWriter(path), format);
		writer.write(doc);
		writer.close();
		
		logger.info("update data success!");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void delete(String path, String collectionName, Object object) throws Exception {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File(path));
		Element root = doc.getRootElement();
		for (Iterator<?> iterator = root.elementIterator("table"); iterator.hasNext();) {
			Element element = (Element) iterator.next();
			if (element.attributeValue("name").equals(collectionName)) {
				for (Iterator<?> iterator2 = element.elementIterator("data"); iterator2.hasNext();) {
					Element data = (Element) iterator2.next();
					Gson gson = new Gson();
					Map<String, String> oldMap = gson.fromJson(data.getText(), Map.class);
					Map<String, String> newMap = gson.fromJson(gson.toJson(object), Map.class);
					if (oldMap.get(Constants._id).equals(newMap.get(Constants._id))) {
						element.remove(data);
					}				
				}
			}
		}

		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(new FileWriter(path), format);
		writer.write(doc);
		writer.close();
		
		logger.info("delete data success!");
	}

	/**
	 * 创建数据库
	 */
	@Override
	public void createDataBase(String path) throws Exception {
		Document document = DocumentHelper.createDocument();
		Element database = document.addElement("database");
		Element table = database.addElement("table");
		table.addAttribute("name", "test");
		Element indexs = database.addElement("table");
		indexs.addAttribute("name", "system.indexs");
		Element users = database.addElement("table");
		users.addAttribute("name", "system.users");
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(new FileWriter(path), format);
		writer.write(document);
		writer.close();
		
		logger.info("create database success!");
	}
	
}
